package android.Lab6_SDcard;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class Lab6_SDcardActivity extends Activity {
	final static String path_name = "/Lab6_SDcard";
	final static String path_sub  = "base/mo";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.i("anhvtex","getSDcardPath()" + getSDcardPath());
        prepareAssets();
    }
    
    String getSDcardPath()
    {
		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + path_name;
    	File tmpFile = new File(path);
		if (!tmpFile.exists()) {
			tmpFile.mkdirs();
		}
    	return path;
    }
    
    private void prepareAssets(String rpath) {

    	String path = getSDcardPath() + "/" + rpath;
		
		File tmpFile = new File(path);
		{
			tmpFile.mkdirs();
	
			AssetManager am = getResources().getAssets();
			String[] filelist;
			try {
				filelist = am.list(rpath);
				
				int length = filelist.length;

				for (int count = 0; count < length; count++) {
					try {
						String currfile = filelist[count];
						Log.d("anhvtex","currfile = " + currfile.toString());
						
						File outfile = new File(path, currfile);

							InputStream is = am.open(rpath + "/" + currfile,
									AssetManager.ACCESS_BUFFER);
							byte[] tempdata = new byte[(int) is.available()];
							is.read(tempdata);
							is.close();
							
							Log.d("anhvtex","Copy from " + rpath + "/" + currfile + " TO "
									+ outfile);
							outfile.createNewFile();
							FileOutputStream fo;
							fo = new FileOutputStream(outfile);
							fo.write(tempdata);
							fo.close();
						
					} catch (Exception e) {
						Log.e("anhvtex","ERROR! " + e);
					}
				}
			} catch (IOException e1) {
				Log.e("anhvtex","SIHome.prepareAssets IOException: " + e1.getStackTrace());
			}
		} 
	}
	
	private void prepareAssets()  {
		String pathArray[] = path_sub.split("/");
		int pathArrayLength = pathArray.length;
		String p = "";
		for (int i = 0; i < pathArrayLength; i++) {
			p += pathArray[i];
			prepareAssets(p);
			p += "/";			
		}
		
	}
   
    
    
}